package com.hup.vd.service.m3u8;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hup.vd.model.selenium.ChromeMessageMatcherConfig;
import com.hup.vd.model.selenium.ChromeMessageMatcherConfig.MyCondition;
import com.hup.vd.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.logging.LogEntry;

import java.util.List;

/**
 * 从Chrome的json字符串日志中匹配m3u8链接
 *
 * @author hugan
 * @date 2022/8/14
 */
@Slf4j
public class ChromeMessageMatcher {

    private final ChromeMessageMatcherConfig config;

    public ChromeMessageMatcher(ChromeMessageMatcherConfig config) {
        this.config = config;
        config.init();
    }

    public String getM3u8Url(List<LogEntry> logs) {
        for (MyCondition condition : config.getConditions()) {
            for (LogEntry logEntry : logs) {
                String message = logEntry.getMessage();
                /*
                &=,位与运算符
                    全部符合 condition.contains才为true
                创建实例时,必须保证condition.contains为非空
                 */
                boolean match = true;
                for (String contain : condition.contains) match &= message.contains(contain);
                if (match) {
                    JSONObject jsonObject = (JSONObject) JSON.parse(message);
                    String m3u8Url = CommonUtil.getJSONObjectString(jsonObject, condition.keys);
                    if (m3u8Url != null) {
                        return m3u8Url;
                    } else {
                        log.warn("匹配规则,但无url, {}", message);
                    }
                }
            }
        }
        return null;
    }
}
